package lib

import (
	"encoding/json"
	"fmt"
	"github.com/iGoogle-ink/gopay"
	"github.com/iGoogle-ink/gopay/wechat"
	"io/ioutil"
	"os"
	"time"
)

//微信配置
type WxPayServer struct {
	AppId string `json:"appId"`
	MchId string `json:"mchId"`
	ApiKey string `json:"apiKey"`

	MobileAppId string `json:"mobileAppId"`

	NotifyUrl string `json:"notifyUrl"`
	Subject  string `json:"subject"`
	OrderNum  string `json:"ordernum"`
	Total  int64 `json:"total"`
	OpenId  string `json:"openid"`
	SchoolName      string  `json:"schoolName"`
}

//微信返回
type WxReturnData struct{
	AppId string `xml:"appid"`
	MchId string `xml:"mch_id"`
	NonceStr string `xml:"nonce_str"`
	PrepayId string `xml:"prepay_id"`
	TradeType string `xml:"trade_type"`
	ReturnCode string `xml:"return_code"`
	ReturnMsg string  `xml:"return_msg"`
	Sign string `xml:"sign"`
	PaySign string `xml:"pay_sign"`
	TimeStamp string `xml:"time_stamp"`
}

var wxPay WxPayServer

/*
 * 描述: 获取微信接口
 *
 *********************************************************************************/
func ( this *WxPayServer )WxPayOrder()(string,error){
	// 初始化微信客户端
	//    appId：应用ID
	//    mchId：商户ID
	//    apiKey：API秘钥值
	fmt.Println(this.Total)
	client := wechat.NewClient(wxPay.AppId, wxPay.MchId, wxPay.ApiKey, true)
	// 初始化 BodyMap
	bm := make(gopay.BodyMap)
	bm.Set("nonce_str", gopay.GetRandomString(32))
	bm.Set("body", wxPay.SchoolName)
	bm.Set("out_trade_no", this.OrderNum)
	bm.Set("total_fee", this.Total)
	bm.Set("spbill_create_ip", "127.0.0.1")
	bm.Set("notify_url", wxPay.NotifyUrl)
	bm.Set("trade_type", wechat.TradeType_Native)
	bm.Set("sign_type", wechat.SignType_MD5)
	sign := wechat.GetParamSign(wxPay.AppId, wxPay.MchId, wxPay.ApiKey, bm)
	bm.Set("sign", sign)
	fmt.Println(bm)
	// ====同步返回参数验签Sign====
	wxRsp, err := client.UnifiedOrder(bm)

	ok, err := wechat.VerifySign(wxPay.ApiKey, wechat.SignType_MD5, wxRsp)
	fmt.Println(ok)
	if ok == true{
		return wxRsp.CodeUrl,err
	}
	return "",err
}

/*
 * 描述: 获取微信接口(APP 支付场景)
 *
 *********************************************************************************/
func ( this *WxPayServer )AppWxPayOrder()(WxReturnData,error){
	// 初始化微信客户端
	//    appId：应用ID
	//    mchId：商户ID
	//    apiKey：API秘钥值
	client := wechat.NewClient(wxPay.MobileAppId, wxPay.MchId, wxPay.ApiKey, true)
	// 初始化 BodyMap
	bm := make(gopay.BodyMap)
	bm.Set("nonce_str", gopay.GetRandomString(32))
	bm.Set("body", wxPay.SchoolName)
	bm.Set("out_trade_no", this.OrderNum)
	bm.Set("total_fee", this.Total)
	bm.Set("spbill_create_ip", "127.0.0.1")
	bm.Set("notify_url", wxPay.NotifyUrl)
	bm.Set("trade_type", wechat.TradeType_App)
	bm.Set("sign_type", wechat.SignType_MD5)
	sign := wechat.GetParamSign(wxPay.MobileAppId, wxPay.MchId, wxPay.ApiKey, bm)
	bm.Set("sign", sign)
	// ====同步返回参数验签Sign====
	wxRsp, err := client.UnifiedOrder(bm)
	ok, err := wechat.VerifySign(wxPay.ApiKey, wechat.SignType_MD5, wxRsp)
	fmt.Println(ok,"支付失败错误信息",err)
	var val WxReturnData
	if ok == true{
		val.AppId = wxPay.MobileAppId
		val.MchId = wxRsp.MchId
		val.ReturnCode = wxRsp.ReturnCode
		val.ReturnMsg = wxRsp.ReturnMsg
		val.PrepayId = wxRsp.PrepayId
		val.NonceStr = wxRsp.NonceStr
		val.TradeType = wxRsp.TradeType
		val.Sign = wxRsp.Sign
		timeStamp := fmt.Sprintf("%d",time.Now().Unix())
		val.TimeStamp = timeStamp
		val.PaySign = wechat.GetAppPaySign(wxPay.MobileAppId,val.MchId, val.NonceStr,val.PrepayId, wechat.SignType_MD5,timeStamp,wxPay.ApiKey )
	}
	return val,err
}
/*
 * 描述: 初始化配置
 *
 *********************************************************************************/
func init(){
	jsonFile, err := os.Open( "./config/paychat.json" )
	if err != nil {
		panic("打开文件错误，请查看:" + err.Error())
	}
	defer jsonFile.Close()
	data, err := ioutil.ReadAll(jsonFile)
	json.Unmarshal( data, &wxPay)
	fmt.Println( "wxpay", wxPay )
}
